<template>
  <div class="appointment-settings">
    <div class="info-box">
      
      <!-- 未来一周日期选择器 -->
      <div class="week-picker">
        <div class="info-title">日期选择</div>
        <div class="dates-grid">
          <div
            v-for="date in futureDates"
            :key="date.date"
            class="date-item"
            :class="{ 
              'selected': selectedDates.includes(date.date),
              'disabled': isDateDisabled(date.date)
            }"
            @click="toggleDate(date.date)"
          >
            <div class="weekday">{{ date.weekday }}</div>
            <div class="date">{{ date.day }}日</div>
            <div class="month">{{ date.month }}月</div>
          </div>
        </div>
      </div>

      <!-- 时间段选择 -->
      <div class="time-slots">
        <el-card class="time-box">
        <div class="info-title">时间段选择</div>
        <el-checkbox-group v-model="selectedTimeSlots">
          <div class="time-row">
            <el-checkbox 
              v-for="period in morningPeriods" 
              :key="period.value"
              :label="period.value"
              :disabled="isTimeSlotDisabled(selectedDates[0], period.value)"
            >
              {{ period.label }}
            </el-checkbox>
          </div>
          <div class="time-row">
            <el-checkbox 
              v-for="period in afternoonPeriods" 
              :key="period.value"
              :label="period.value"
              :disabled="isTimeSlotDisabled(selectedDates[0], period.value)"
            >
              {{ period.label }}
            </el-checkbox>
          </div>
        </el-checkbox-group>
        </el-card>
      </div>

      <div class="btn">
        <el-button type="primary" @click="handleSubmit" :loading="loading">设 置</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserInfoStore } from '@/stores/info'
import ScheduleApi from '@/api/schedual'
import type { Schedule } from '@/api/schedual/types'

const userInfoStore = useUserInfoStore()
const loading = ref(false)

// 已存在的排班记录
const existingSchedules = ref<Schedule[]>([])

// 时间段定义
const morningPeriods = [
  { value: 1, label: '8：00-8：50' },
  { value: 2, label: '9：00-9：50' },
  { value: 3, label: '10：00-10：50' },
  { value: 4, label: '11：00-11：50' }
]

const afternoonPeriods = [
  { value: 5, label: '14：00-14：50' },
  { value: 6, label: '15：00-15：50' },
  { value: 7, label: '16：00-16：50' }
]

// 格式化日期为 YYYY-MM-DD
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr)
  return date.toISOString().split('T')[0]
}
// 获取已有排班
const getExistingSchedules = async () => {
  try {
    const res = await ScheduleApi.getSchedules({
      user_id: userInfoStore.userInfo.user_id,
      is_delete: 0
    })
    if (res) {
      if (Array.isArray(res.data)) {
        existingSchedules.value = res.data
      } else {
        ElMessage.error('获取排班失败')
      }
    }
  } catch (error) {
    console.error('获取排班失败:', error)
  }
}

// 检查时间段是否已被占用
const isTimeSlotDisabled = (date: string, period: number) => {
  if (!date) return true
  return existingSchedules.value.some(schedule => 
    formatDate(String(schedule.date)) === date && 
    schedule.period === period && 
    schedule.is_delete === 0
  )
}

// 检查日期是否已全部被占用
const isDateDisabled = (date: string) => {
  const dateSchedules = existingSchedules.value.filter(schedule => 
    formatDate(String(schedule.date)) === date && 
    schedule.is_delete === 0
  )
  return dateSchedules.length >= 7 // 所有时间段都被占用
}

// 星期几的映射
const weekdayMap = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

// 获取未来7天的日期
const futureDates = computed(() => {
  const dates = []
  const today = new Date()
  
  for (let i = 1; i <= 7; i++) {
    const date = new Date(today)
    date.setDate(today.getDate() + i)
    
    dates.push({
      date: date.toISOString().split('T')[0], // YYYY-MM-DD
      weekday: weekdayMap[date.getDay()],
      day: date.getDate(),
      month: date.getMonth() + 1
    })
  }
  
  return dates
})

// 选中的日期
const selectedDates = ref<string[]>([])

// 选中的时间段
const selectedTimeSlots = ref<number[]>([])

// 切换日期选择
const toggleDate = (date: string) => {
  if (isDateDisabled(date)) return
  
  // 只允许选择一个日期
  selectedDates.value = selectedDates.value.includes(date) ? [] : [date]
  
  // 清空时间段选择
  selectedTimeSlots.value = []
}

// 提交设置
const handleSubmit = async () => {
  if (selectedDates.value.length === 0) {
    ElMessage.warning('请选择至少一个日期')
    return
  }
  if (selectedTimeSlots.value.length === 0) {
    ElMessage.warning('请选择至少一个时间段')
    return
  }

  loading.value = true
  try {
    const scheduleList: Partial<Schedule>[] = []
    
    selectedDates.value.forEach(date => {
      selectedTimeSlots.value.forEach(period => {
        scheduleList.push({
          user_id: userInfoStore.userInfo.user_id,
          date,
          period, 
          status: 0,  // 0表示可预约
          is_delete: 0
        })
      })
    })

    const res = await ScheduleApi.createSchedules(scheduleList)
    
    if (res) {
      ElMessage.success('排班设置成功')
      // 清空选择
      selectedDates.value = []
      selectedTimeSlots.value = []
      // 重新获取排班数据
      await getExistingSchedules()
    } else {
      ElMessage.error('排班设置失败')
    }
  } catch (error) {
    console.error('排班设置失败:', error)
    ElMessage.error('排班设置失败')
  } finally {
    loading.value = false
  }
}

// 在组件挂载时获取数据
onMounted(async () => {
  await getExistingSchedules()
})
</script>

<style scoped>
.week-picker {
  margin: 20px 0;
  padding: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.dates-grid {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

.date-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px 10px;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.date-item:hover {
  border-color: #409eff;
  background-color: #f5f7fa;
}

.date-item.selected {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
}

.weekday {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.date {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 5px;
}

.month {
  font-size: 14px;
  color: #666;
}

.date-item.selected .month {
  color: white;
}

/* 保留原有的其他样式 */
.info-box {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.info-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.time-row {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-bottom: 15px;
  font-size: 18px;
}

.btn {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

:deep(.el-button) {
  font-size: 18px;
  padding: 12px 40px;
  height: auto;
}

:deep(.el-checkbox__label) {
  font-size: 18px;
}

.date-item.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.date-item.disabled:hover {
  border-color: #dcdfe6;
  background-color: transparent;
}
</style>
